import src from './source'

//获取发票云token
export const getInvoiceCloudToken = (params = {}) => {
    src.API_REQ.getInvoiceCloudToken(params).then(res => {
        // let res = {
        //     "invoiceCloud": true,
        //     "jsUrl": "https://im.mulinquan.cn:434",
        //     "baseUrl": "https://im.mulinquan.cn:434",
        //     // "token": "-NYP5uT5Pxg0nzXO3D6xO25Ad4P3GIDrdo6LzbY9LlA",
        //     "token": "u5iLMGnjcAkZi163OVhDG25Ad4P3GIDrdo6LzbY9LlA",
        //     "status": "1",
        //     "info": ""
        // };
        let { invoiceCloud = false, errorInfo, status } = res;
        const { setInvoiceCloudInfo } = src.globalStore;
        if (status !== '-1') {
            if (invoiceCloud) {//发票云
                if (errorInfo) { //无权限

                } else {
                    setInvoiceCloudInfo({
                        token: res.token,
                        invoiceCloud: invoiceCloud,
                        jsUrl: res.jsUrl,
                        baseUrl: res.baseUrl,
                    })
                }
            }
        }
    })
}

//ecid转fid
export const getInvoiceFid=(params={})=>{
   return new Promise(resolve=>{
        src.API_REQ.getFidOrEcid(params).then(res => {
            resolve(res)
        })
    })
}


//发票云页面选中数据后的回调函数
const selectedCallback = (res) => {
    const { changeSingleFieldValue, fieldAttrMap } = src.layoutStore;
    if (src.isMobile) {//移动端发票云
        const { originParams = {} } = res;
        const { fieldMark } = originParams;
        if (res.type === "INVOICE" && fieldMark) {
            const { invoices } = res;
            let fieldid = fieldMark.substr(0, 5);
            let rowIndex = -1;
            if (fieldid.indexOf("_") > -1) {
                fieldid = fieldid.split("_")[0];
                rowIndex = fieldid.split("_")[1];
            }
            const fieldAttr = fieldAttrMap.get(fieldid);
            let valueInfo = getInvoiceObj(invoices);
            changeSingleFieldValue(fieldMark, valueInfo, {});
            window.historyRoute.go(-1)
        }

    } else {//pc端发票云
        const { seq = {} } = res;
        const { fieldMark } = seq;
        if (res.type === "retData" && fieldMark) {
            const { datas } = res;
            let fieldid = fieldMark.substr(0, 5);
            let rowIndex = -1;
            if (fieldid.indexOf("_") > -1) {
                fieldid = fieldid.split("_")[0];
                rowIndex = fieldid.split("_")[1];
            }
            const fieldAttr = fieldAttrMap.get(fieldid);
            let valueInfo = getInvoiceObj(datas);
            changeSingleFieldValue(fieldMark, valueInfo, {});
            //关闭弹窗
            window.invoiceBrowser.close();
            window.invoiceBrowser = null;
        } else if (res.type === "close" && fieldMark) {
            window.invoiceBrowser.close();
            window.invoiceBrowser = null;
        }
    }
    if (res.type === "ERROR" ) {
        if (res.ret === -2) {//token失效
            getInvoiceCloudToken({ tokenUnusual: 1 });
        }
    }
}

// 绑定发票云message事件，监听发票云页面回传的数据
export const bindOnMessage = () => {
    window.addEventListener('message', receiver, false);
}

//解除绑定发票云message事件
export const unbindOnMessage = () => {
    window.removeEventListener('message', receiver, false);
}

const receiver = (event) => {
    let returnData = event.data;
    selectedCallback(returnData)
}

const getInvoiceObj = (datas = []) => {
    let ids = [];
    let names=[];
    let specialobj = []
    if (src.isMobile) {
        datas.map(item => {
            ids.push(item.oaid);
            names.push(item.id);
            specialobj.push({
                id: item.oaid,
                name: item.id,
                prop:{
                    cloudId: item.id
                }
            })
        })
    } else {
        datas.map(item => {
            ids.push(item.oa.id);
            names.push(item.id);
            specialobj.push({
                id: item.oa.id,
                name: item.id,
                prop:{
                    cloudId: item.id
                }
            })
        })
    }
    return {
        value: ids.join(","),
        name:names.join(","),
        specialobj: specialobj
    }
}